import React, { useReducer, useEffect, useState } from "react";
import queryApi from "../../api/query";

const MaterialContext = React.createContext();

const dataReducer = (state, action) => {
  switch (action.type) {
    case "fetch_init":
      return action.payload;
    default:
      return state;
  }
};

export const MaterialProvider = ({ children }) => {
  const [isMaterialLoading, setIsMaterialLoading] = useState(false);
  const [isMaterialError, setIsMaterialError] = useState(false);
  const initData = [{ category: "", types: [] }];
  const [Material, dispatch] = useReducer(dataReducer, initData);

  useEffect(() => {
    const fetchData = async () => {
      setIsMaterialLoading(true);
      setIsMaterialError(false);
      try {
        const result = await queryApi.get("/material");
        // console.log("行业内材料--", result.data.message);
        if (result.data.message.length == 0) {
          dispatch({ type: "fetch_init", payload: initData });
        } else {
          dispatch({ type: "fetch_init", payload: result.data.message });
        }
      } catch (err) {
        console.log(err);
        setIsMaterialError(true);
      }
      setIsMaterialLoading(false);
    };
    fetchData();
  }, []);

  return (
    <MaterialContext.Provider
      value={{ material: Material, isMaterialError, isMaterialLoading }}
    >
      {children}
    </MaterialContext.Provider>
  );
};

export default MaterialContext;
